import cv2
import matplotlib.pyplot as plt


def show_img(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


img = cv2.imread('pandas.jpg')
heart_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

"""
    cv2.threshold(src, thresh, maxval, type)
    src: 输入图像
    thresh: 阈值 (一般为127)
    maxval: 超过阈值部分的像素值
    type: 
        二值化方法： 
            cv2.THRESH_BINARY,          超过阈值部分取maxval(取最大值) 否则为0(黑色) 突出背景
            cv2.THRESH_BINARY_INV,      超过阈值部分为0(黑色) 否则为maxval(取最大值) 突出目标
            cv2.THRESH_TRUNC,           超过阈值部分设为阈值 否则不变
            cv2.THRESH_TOZERO,          超过阈值部分不变 否则设置为0
            cv2.THRESH_TOZERO_INV       超过阈值部分设置为0 否则不变
"""

# ret: 阈值 thresh: 结果(三维数组) 255(白色)
ret_binary, binary = cv2.threshold(heart_img, 127, 255, cv2.THRESH_BINARY)
ret_binary_inv, binary_inv = cv2.threshold(heart_img, 127, 255, cv2.THRESH_BINARY_INV)
ret_trunc, trunc = cv2.threshold(heart_img, 127, 255, cv2.THRESH_TRUNC)
ret_to_zero, to_zero = cv2.threshold(heart_img, 127, 255, cv2.THRESH_TOZERO)
ret_to_zero_inv, to_zero_inv = cv2.threshold(heart_img, 127, 255, cv2.THRESH_TOZERO_INV)

title = ['PandasGray', 'Binary', 'BinaryInv', 'Trunc', 'ToZero', 'ToZeroInv']
images = [heart_img, binary, binary_inv, trunc, to_zero, to_zero_inv]

# 使用matplotlib显示图像，并设置色彩映射为'gray'
plt.figure(figsize=(10, 8))  # 可以调整图像大小
for i in range(6):
    plt.subplot(2, 3, i + 1)
    plt.imshow(images[i], 'gray')  # 确保使用'gray'色彩映射
    plt.title(title[i])
    plt.xticks([]), plt.yticks([])

plt.tight_layout()  # 调整子图间距
plt.show()
